import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:simple_app/chat.dart';
import 'package:simple_app/common/api.dart';
import 'package:simple_app/common/global.dart';
import 'package:simple_app/common/message/notify.dart';
import 'package:simple_app/common/model/friend.dart';

class FriendsListPage extends StatefulWidget {
  const FriendsListPage({Key? key}) : super(key: key);

  @override
  State<FriendsListPage> createState() => _FriendsListPageState();
}

class _FriendsListPageState extends State<FriendsListPage> {
  var itemCount = 0;
  List<Friend> list = [];

  //列表数据
  Future<void> getList() async {
    var r = await Api().friendList();
    if (r == null) {
      return;
    }
    if (r.statusCode != 200) {
      return;
    }
    if (r.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(r.body);
      if (data['status'] == 1) {
        List<dynamic> list2 = data['list'];
        setState(() {
          list.clear();
          for (var element in list2) {
            list.add(Friend.fromJson(element));
          }
          itemCount = list.length;
        });
      }
    }
    return;
  }

  var listenid = -1;

  //获取双向通讯信息
  receiveMessage(jsonObj) {
    if (jsonObj['type'] == 'notify') {
      var data = Notify.fromJson(jsonObj);
      if (data.data['method'] == 'online') {
        var friendid = data.data['userid'];
        var index = -1;
        setState(() {
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            if (item.friendId == friendid) {
              list.insert(
                  i,
                  Friend(
                      friendId: item.friendId,
                      name: item.name,
                      onlineState: 1));
                      break;
            }
          }
        });
        if (index != -1) {
          setState(() {
            list.removeAt(index);
          });
        }
      }
      if (data.data['method'] == 'offline') {
        var friendid = data.data['userid'];
        var index = -1;
        setState(() {
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            if (item.friendId == friendid) {
              list.insert(
                  i,
                  Friend(
                      friendId: item.friendId,
                      name: item.name,
                      onlineState: 0));
                      break;
            }
          }
        });
        if (index != -1) {
          setState(() {
            list.removeAt(index);
          });
        }
      }
    }
  }

  @override
  void initState() {
    super.initState();
    getList();
    if (listenid == -1) {
      listenid = Global.listenMessage(receiveMessage);
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (listenid != -1) {
      Global.removeListenMessage(listenid);
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        onRefresh: onRefresh,
        child: ListView.builder(
            itemCount: itemCount,
            itemBuilder: (context, index) {
              const online = Text(
                '在线',
                style: TextStyle(color: Color.fromARGB(255, 0, 200, 0)),
              );
              const offline = Text(
                '离线',
                style: TextStyle(color: Color.fromARGB(255, 200, 0, 0)),
              );
              return GestureDetector(
                child: ListTile(
                  title: Text(list[index].name),
                  subtitle: list[index].onlineState == 1 ? online : offline,
                ),
                onTap: () {
                  //点击进入chat页面
                  print(index);
                  var cur = list[index];
                  Navigator.pushNamed(context, "/chat",
                      arguments:
                          ChatRouteArgs(name: cur.name, id: cur.friendId));
                },
              );
            }));
  }

  Future<void> onRefresh() {
    return getList();
  }
}
